var express = require('express')

var router = express.Router()

const { getOne, getAll, exec } = require('../db')

router.get('/', async (req, res) => {
	const { page, size } = req.query
	const offset = (page - 1) * size
	// SELECT * FROM event_notice WHERE notice_status LIKE 0 LIMIT 1,10
	let sql = `select * from event_notice  where notice_status= 1 order by id desc limit ${offset},${size}  `
	const data = await getAll(sql)
	sql = `select count(*) as total from event_notice where notice_status= 1`
	const { total } = await getOne(sql)
	res.send({
		code: 0,
		message: '获取所有公告成功',
		result: {
			total,
			data,
		},
	})
})

/**
 * 获取单个公告信息
 * GET /notices/:id
 */
router.get('/:id', async (req, res) => {
	const { id } = req.params

	let sql = `select * from event_notice where id=${id}`
	const data = await getOne(sql)
	res.send({
		code: 0,
		message: '获取单个公告成功',
		result: data,
	})
})

/**
 * 发布公告
 * POST /notices
 */
router.post('/', async (req, res) => {
	const { user_id, notice_title, notice_content } = req.body
	const publish_time = new Date().toLocaleDateString()

	let sql = `insert into event_notice(user_id, notice_title, notice_content, publish_time) values(${user_id}, '${notice_title}', '${notice_content}', '${publish_time}')`
	const data = await exec(sql)
	res.send({
		code: 0,
		message: '发布公告成功',
		result: data,
	})
})

/**
 * 删除公告
 * PUT /notices/:id
 */
router.put('/:id', async (req, res) => {
	const { id } = req.params
	// console.log(req.body);
	const { notice_status } = req.body
	let sql = `update event_notice set  notice_status='${notice_status}' where id=${id}`
	const data = await exec(sql)
	res.send({
		code: 0,
		message: '删除公告成功',
		result: data,
	})
})

module.exports = router
